package com.guoxin.chapter1;

/**
 * 非线程安全主要是指多个线程对同一个对象中的同一实例变量进行操作时候会出现值被更改、值不同的情况
 *
 * @author guoxin
 * @date 2019/8/8
 */
public class UnsafeThread {

    public static void main(String[] args) {
        new ALogin().start();
        new BLogin().start();
    }

}

class LoginServlet {
    private static String usernameRef;
    private static String passwordRef;

    public  static void doPost(String username, String password) {
        try {
            usernameRef = username;
            if ("a".equals(username)) {
                Thread.sleep(500);
            }
            passwordRef = password;
            System.out.println("username=" + usernameRef + " password=" + passwordRef);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized static void doPost2(String username, String password) {
        try {
            usernameRef = username;
            if ("a".equals(username)) {
                Thread.sleep(500);
            }
            passwordRef = password;
            System.out.println("username=" + usernameRef + " password=" + passwordRef);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ALogin extends Thread {
    @Override
    public void run() {
        LoginServlet.doPost("a", "aa");
    }
}

class BLogin extends Thread {
    @Override
    public void run() {
        LoginServlet.doPost("b", "bb");
    }
}